<template>
  <div class="login">
    <van-form @submit="submitForm">
      <van-field
        v-model="user.userName"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="user.password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">登录</van-button>
        <van-button round block type="primary" @click="register" style="margin-top: 10px;">注册</van-button>
        <van-button round block type="primary" @click="loginStore.clearLoginInfo()" style="margin-top: 10px;">退出</van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { useLoginStore } from '@/stores/loginStore';
import request from '@/utils/request';
import { showToast } from 'vant';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const loginStore = useLoginStore();

const user = ref({
  userName: 'liarjo',
  password: '123456',
});

const submitForm = async () => {
  try {
    const response = await request.post('/api/login', {
      userName: user.value.userName,
      password: user.value.password,
    });
    const loginResult = response.data;
    loginStore.setLoginInfo(loginResult);
    router.push('/');
  } catch (error) {
    console.error(error);
    showToast({
      message: '登录失败',
      duration: 2000
    });
  }
};

const register = async () => {
  try {
    const response = await request.post('/api/register', {
      userName: user.value.userName,
      password: user.value.password,
    });
    const registerResult = response.data;
    showToast({
      message: '注册成功',
      duration: 2000
    });
    loginStore.setLoginInfo(registerResult);
    router.push('/');
  } catch (error) {
    console.error(error);
    showToast({
      message: '注册失败',
      duration: 2000
    });
  }
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
</style>